package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Deal;
import cn.hd01.service.CustomerService;
import cn.hd01.service.DealService;
import cn.hd01.web.auth.Auth;

@Auth
@Controller
@RequestMapping("/deal")
public class DealController {

	@Autowired
	private DealService dealSerivce;

	@Autowired
	private CustomerService customerService;

	@RequestMapping(path = "/{customerId}", method = RequestMethod.GET)
	public String index(@PathVariable("customerId") Integer customerId, Model m) {
		m.addAttribute("customer", customerService.findOne(customerId));
		m.addAttribute("menu", "/customer/");
		return "deal";
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	public void save(Deal entity) {
		if (!entity.getAgree()) {
			entity.setPrice(null);
			entity.setProduct(null);
		}
		dealSerivce.save(entity);
	}

	@ResponseBody
	@RequestMapping(path = "/{customerId}/list", method = RequestMethod.GET)
	private Page<Deal> find(@PathVariable("customerId") Integer customerId, @PageableDefault Pageable pageable) {
		return dealSerivce.findAll(customerId, pageable);
	}

}
